<template>
  <view class="lottery-grid-comp">
    <view class="text" @click="openLottery">
      <view class="buttonAnimate">
        <image style="width: 100rpx" src="./image/prize/click-lottery2.png" mode="widthFix"></image>

        <!-- 角标 -->
        <view class="badge">{{
          myLottery.info && job.info
            ? job.info.drawType === 1
              ? myLottery.info.canLimit
              : myLottery.info.lotteryCount
            : 0
        }}</view>
      </view>
    </view>
    <popup ref="popup" style="z-index: 991" :isMaskClick="true" @change="popupChange">
      <view class="popup-content" style="position: relative">
        <LuckyWheel
          ref="myLucky"
          width="600rpx"
          height="600rpx"
          :rows="rows"
          :cols="cols"
          :blocks="blocks"
          :prizes="prizes"
          :buttons="buttons"
          :defaultStyle="defaultStyle"
          :activeStyle="activeStyle"
          @start="startCallBack"
          @end="endCallBack"
        />

        <view class="time-box">
          <p>
            您还有
            {{
              myLottery.info && job.info
                ? job.info.drawType === 1
                  ? myLottery.info.canLimit
                  : myLottery.info.lotteryCount
                : 0
            }}
            次抽奖机会
          </p>
        </view>

        <!-- <view class="time-box flex items-center justify-center" @click="$refs.readTaskRef.open()">
          <text class="dyicon icon-hand-replace icon-style"></text
          ><text style="display: inline-block; color: #fff420; text-decoration: underline"
            >阅读三篇文章</text
          >可兑换1次抽奖机会
        </view> -->

        <my-prize
          v-if="config"
          ref="myPrizeRef"
          style="position: relative; right: 0; display: flex; justify-content: flex-end"
          :jobId="config.configJson.lottery.id"
        ></my-prize>
        <view class="to-my-card">
          <image
            src="https://wxlsrecode2.oss-cn-shanghai.aliyuncs.com/coupon_model/2023-12-21/71871692-a050-423d-8b3d-05590e24dcb8.png"
            mode="widthFix"
            @click="toMyCard"
          ></image>
        </view>

        <view class="close-btn" @click="close">
          <text class="dyicon icon-guanbi"></text>
        </view>
      </view>
    </popup>

    <!-- 阅读任务前置 -->
    <!-- <readTask
      ref="readTaskRef"
      @close="
        addVoteNum(2);
        $refs.readTaskRef.close();
      "></readTask> -->
  </view>
</template>

<script>
  import { mapGetters } from 'vuex';
  import * as Api from '@/server/index.js';
  import * as Utils from '@/utils/index.js';
  import popup from '@/components/popup/index.vue';
  import LuckyWheel from '@/components/@lucky-canvas/uni/lucky-wheel.vue'; // 九宫格
  // import readTask from '@/components/readTask/index.vue';
  import myPrize from './components/myPrize/myPrize.vue';

  // const isUniapp = process.env.NODE_ENV === 'development' ? true : Utils.util.isUniapp();
  const isUniapp = Utils.util.isUniapp();

  export default {
    name: 'lotteryGridComp',
    components: {
      popup,
      LuckyWheel,
      // readTask,
      myPrize,
    },
    props: {
      description: {
        type: String,
        require: true,
      },
      isCan: {
        type: Boolean,
        default: false,
      },
      /**
       * 是否打开就请求添加资格到可抽奖指定名单
       */
      isOpenAddLotteryCount: {
        type: Boolean,
        require: true,
      },
    },
    data() {
      return {
        configInfo: null, // 页面配置信息
        rows: 3, // 设置布局行
        cols: 3, // 设置布局列
        blocks: [
          {
            padding: '38rpx', // 上下左右
            imgs: [
              {
                src: require('./image/prize/bg2.png'),
                width: '100%',
                height: '100%',
                rotate: true,
              },
            ],
          },
        ],
        prizes: [],
        buttons: [],
        activeStyle: {
          background: 'linear-gradient(to bottom, #ffcba0, #ffcba0);',
        },
        defaultStyle: {
          background: 'linear-gradient(to bottom, #FEFEFE, #F8D0C3);',
        },
        defaultConfig: {
          gutter: '10rpx', // 格子间的缝隙
          speed: 10, //旋转速度峰值
          accelerationTime: 5000, // 开始旋转时间
          decelerationTime: 10000, // 缓慢停止时间
        },

        job: {
          info: null, // 活动详情
          optionList: [], // 奖品选项
          userList: [], // 中奖名单
        },
        myLottery: {
          list: [],
          info: null,
        }, // 个人中奖信息
      };
    },
    computed: {
      ...mapGetters(['token', 'config']),
    },
    async mounted() {
      await this.$onLaunched;
      await this.pageLotteryModule(); // 分页查询抽奖模板（获取页面配置信息）
      this.init_load();
    },
    methods: {
      // 分页查询抽奖模板（获取页面配置信息）
      async pageLotteryModule() {
        const params = {
          current: 1,
          size: 1,
          lotteryJobId: this.config.configJson.lottery.id,
        };
        try {
          const { data: res } = await Api.lottery.pageLotteryModule(params);
          res.data.items[0].carousel = res.data.items[0].carousel.split(',');
          if (res.data.items[0].configJson)
            res.data.items[0].configJson = JSON.parse(res.data.items[0].configJson);
          this.configInfo = res.data.items[0];
          this.blocks[0].imgs[0].src = this.configInfo.wheelDisc;
          // this.blocks[0].padding = this.configInfo.configJson.blocks.padding;
          this.blocks[0].padding = '60rpx'; // TODO
          this.buttons = [
            {
              radius: '45%',
              imgs: [
                {
                  src: this.configInfo.button,
                  width: this.configInfo.configJson.buttons.width,
                  top: this.configInfo.configJson.buttons.top,
                },
              ],
            },
          ];
        } catch (e) {}
      },
      async init_load() {
        await this.getJob(); // 获取活动
        this.getOption(); // 获取奖品列表
        await this.getLotteryCount(); // 获取用户剩余可抽奖次数
        if (this.isOpenAddLotteryCount && this.job.info.drawType === 1) this.setRoster(); // 打开就请求添加资格到可抽奖指定名单
      },
      /**
       * 获取抽奖活动信息
       */
      async getJob() {
        const params = {
          current: 1,
          size: 1,
          id: this.config.configJson.lottery.id,
        };
        try {
          const { data: res } = await Api.lottery.getJob(params);
          this.job.info = res.data.items[0];
        } catch (e) {
          console.log('获取抽奖活动信息', e);
        }
      },

      /**
       * 获取奖品列表
       */
      async getOption() {
        try {
          const { data: res } = await Api.lottery.getOption(this.config.configJson.lottery.id);
          this.job.optionList = res.data;
          const arr = Utils.util.classifyArr(res.data, (item) => item.assortName);
          const prizes = []; // 转盘奖品配置
          for (let index in arr) {
            const item = arr[index];
            prizes.push({
              assortName: item[0].assortName,
              list: item,
              background: index % 2 === 0 ? '#FFF4F4' : '#FFFFFF',
              imgs: [
                {
                  src: item[0].image,
                  width: this.configInfo.configJson.prizes.width,
                  top: this.configInfo.configJson.prizes.top,
                },
              ],
            });
          }
          this.prizes = prizes;
        } catch (e) {
          console.log('获取奖品列表', e);
        }
      },
      /**
       * 初始化九宫格
       */
      init() {
        this.$refs.myLucky.init();
      },
      /**
       * 点击抽奖按钮触发回调
       */
      async startCallBack() {
        // 判断有无资格抽奖
        if (!(await this.checkCanLottery())) return;
        if (!isUniapp && uni.getStorageSync('viewType') !== 'dev')
          return Utils.Msg.Alert('请使用源新闻抽奖！', '提示');

        if (this.lotteryMask) return;
        this.lotteryMask = true;
        // 假设后端返回的中奖索引是0
        let index = -1;
        const res = await this.lottery();
        // TODO
        /* const res = {
          data: {
            id: 303,
            lotteryOptionId: 303,
            isAlive: 1,
            createBy: 60065,
            createTime: '2024-01-05 14:21:18',
            updateBy: 60065,
            updateTime: '2024-01-05 15:24:10',
            lotteryJobId: 114,
            lotteryPrize: '全场通用20元券',
            lotteryProbability: 20,
            lotteryAwardId: 0,
            lotterySum: 200,
            isDayLottery: 1,
            isDayLimit: 20,
            image:
              'https://wxlsrecode2.oss-cn-shanghai.aliyuncs.com/lottery_model/2024-01-05/4ae22329-6edb-4ecb-9117-56bd1d892596.png',
            isDayManLimit: 1,
            isDayManLottery: 1,
            angle: 0,
            isBatches: 0,
            assortName: '3',
          },
        }; */
        if (res === false) return;
        if (!res.data) {
          // 未中奖
          index = this.prizes.findIndex((item) => item.assortName === '谢谢惠顾');
        }
        if (res.data) {
          // 中奖操作
          index = this.prizes.findIndex((item) => item.assortName === res.data.assortName);
          this.tempOtion = res.data;
        }
        console.log('index', index);
        if (index === -1) {
          index = this.prizes.findIndex((item) => item.assortName === '谢谢惠顾');
        }
        // 先开始旋转
        this.$refs.myLucky.play();
        // 使用定时器来模拟请求接口
        const timer = setTimeout(() => {
          clearTimeout(timer);
          // 调用stop停止旋转并传递中奖索引
          this.$refs.myLucky.stop(index);
        }, 3000);
      },
      /**
       * 抽奖结束触发回调
       * @param {Object} prize
       */
      endCallBack(prize) {
        // 奖品详情
        console.log(prize);
        const timer = setTimeout(() => {
          clearTimeout(timer);
          this.lotteryMask = false;
          if (prize.assortName === '谢谢惠顾') {
            uni.showModal({
              content: '抱歉您未中奖！',
              showCancel: false,
            });
            return;
          }

          // 实时开奖时会提示
          const item = prize.list.find((item) => item.id === this.tempOtion.lotteryOptionId);
          uni.showModal({
            content: `恭喜您，抽中${item.lotteryPrize}!`,
            showCancel: false,
            success: (re) => {
              this.tempOtion = null;
              this.$refs.myPrizeRef.getMyPrize();
            },
          });
        }, 800);
      },

      /**
       * 抽奖
       */
      async lottery() {
        Utils.Msg.ShowLoading(true, '加载中...');
        let params = null;
        try {
          const { data: res } = await Api.lottery.lottery(this.config.configJson.lottery.id);
          // console.log('抽奖---', res);
          if (!res.success && res.message.includes('没有抽奖资格')) {
            Utils.Msg.Alert('先投票，才能获取抽奖资格！');
            this.lotteryMask = false;
            return false;
          }

          // 是否名单内限制判断
          if (this.job.info.drawType === 1) this.myLottery.info.canLimit--;
          if (this.job.info.drawType === 0) this.myLottery.info.lotteryCount--;
          return res;
        } catch (e) {
          this.lotteryMask = false;
          return false;
        } finally {
          Utils.Msg.HideLoading();
        }
      },

      /**
       * 判断有无资格抽奖
       */
      async checkCanLottery() {
        try {
          console.log('判断有无资格抽奖');
          return true;
        } catch (e) {
          return false;
        }
      },

      /**
       * 添加资格到可抽奖指定名单
       */
      async setRoster() {
        Utils.Msg.ShowLoading(true);
        try {
          const { data: res } = await Api.lottery.setRoster(this.config.configJson.lottery.id);
          // console.log('添加资格到可抽奖指定名单---', res);
          Utils.Msg.HideLoading();
          this.myLottery.info.canLimit++;
          return true;
        } catch (e) {
          Utils.Msg.HideLoading();
          return false;
        } finally {
        }
      },

      /**
       * 兑换获取抽奖次数
       * @param {Boolean} tip 接口请求成功是否提示
       */
      async toGetLotteryNum(tip = true) {
        try {
          const { data: res } = await Api.lottery.setRosterLimit(this.config.configJson.lottery.id);
          console.log('res', res.data);
          this.myLottery.info.canLimit++;
          tip && Utils.Msg.ShowToast('兑换成功！');
          // this.$refs.readTaskRef.close();
          return true;
        } catch (e) {
          return false;
        }
      },

      // 获取用户剩余可抽奖次数
      async getLotteryCount() {
        uni.showLoading();
        try {
          // const { data: res } = await Api.lottery.getRosterLimit(this.config.configJson.lottery.id); // 抽奖前置限制的抽奖次数
          const { data: res } =
            this.job.info.drawType === 1
              ? await Api.lottery.getRosterLimit(this.config.configJson.lottery.id)
              : await Api.lottery.getLotteryCount(this.config.configJson.lottery.id); // 通用的抽奖次数
          this.myLottery.info = res.data || {
            canLimit: 0,
            lotteryCount: 0,
          };
        } catch (e) {
        } finally {
          uni.hideLoading();
        }
      },

      async openLottery() {
        // if (!this.isCan) return Utils.Msg.Alert('请先参与投票！', '提示');
        await this.getLotteryCount();
        this.open();
      },

      /**
       * 增加票数(type 1进入增加票； 2阅读增加3票)
       */
      async addVoteNum(type) {
        try {
          const { data: res } = await Api.index.addVoteNum(type);
          type === 2 && Utils.Msg.ShowToast('兑换成功');
        } catch (e) {}
      },

      // 跳转个人卡包
      toMyCard() {
        const url = encodeURIComponent(
          `https://wap2.wxls.pro/coupon/#/pages/coupon/myCoupon?commodityType=0`,
        );
        h5uni.navigateTo({
          url: `/pages/webview/index?url=${url}`, // 跳转个人卡包
        });
      },

      popupChange(e) {
        if (!e.show) {
          this.lotteryMask = false;
        }
      },

      open() {
        this.$refs.popup.open();
      },
      close() {
        this.$refs.popup.close();
      },
    },
  };
</script>

<style lang="scss" scoped>
  .lottery-grid-comp {
    position: relative;
  }
  .text {
    position: fixed;
    right: 16rpx;
    top: 63%;
    z-index: 9;
    .badge {
      position: absolute;
      top: -12rpx;
      right: -6rpx;
      width: 34rpx;
      height: 36rpx;
      color: #fff;
      font-size: 24rpx;
      background-color: #ff5f56;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      border: 1px solid #fff;
    }
  }

  .popup-content {
    position: relative;
    width: 90%;
    max-height: 80vh;
    padding: 20rpx;
    border-radius: 24rpx;
    background-image: url('./image/prize/bg1.png');
  }
  .scroll-view {
    width: 100%;
    height: 100%;
  }
  .product_desc {
    overflow: hidden;
    background-color: #fff;
    padding: 20rpx 30rpx;
    font-size: 28rpx;
    line-height: 1.75;
    // color: #aaa2a2;
    color: #666;

    /deep/ img,
    p,
    span {
      max-width: 100% !important;
      height: auto !important;
    }
    /deep/ p {
      margin: 2rpx 0;
    }
  }

  .time-box {
    margin-top: 30rpx;
    font-size: 28rpx;
    color: #fff;
    text-align: center;
  }

  .time {
    margin-left: 10rpx;
    font-size: 28rpx;
    color: #ff5f56;
  }
  .icon-style {
    display: inline-block;
    color: #fff;
    font-size: 36rpx;
    transform: rotate(90deg);
    margin-right: 8rpx;
  }

  .to-my-card {
    position: absolute;
    left: 50%;
    bottom: 28rpx;
    transform: translateX(-50%);
    width: 240rpx;
    display: flex;
    justify-content: center;
    align-items: center;

    image {
      width: 100%;
    }
  }

  .close-btn {
    position: absolute;
    top: 16rpx;
    right: 16rpx;
    width: 32rpx;
    height: 32rpx;
    font-size: 32rpx;
    line-height: 32rpx;
    color: #fff;
  }
</style>
